package com.changgo.web.filter;

import com.changgo.web.service.AutoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    public static final String Authorization = "Authorization";

    private static final String LOGIN_URL = "http://localhost:9201/oauth/toLogin";
    @Autowired
    private AutoService autoService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        //判断当前请求路径
        if (path.equals("/api/oauth/login") || !URLFilter.hasAuthorize(path)) {
            return chain.filter(exchange);
        }
        //判断请求头中是否包含token
        //判断cookie上是否存在jti
        String jti = autoService.getJtiFromCookie(request);
        if (StringUtils.isEmpty(jti)) {
            //拒绝访问,请求跳转
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return toLoginPage(LOGIN_URL, exchange);
        }

        //判断redis中token是否存在
        String redisToken = autoService.getTokenFromRedis(jti);
        if (StringUtils.isEmpty(redisToken)) {
            //拒绝访问，请求跳转
            //response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return toLoginPage(LOGIN_URL + "?FROM=" + request.getURI(), exchange);
        }
        request.mutate().header(Authorization, "Bearer " + redisToken);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> toLoginPage(String loginUrl, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location", loginUrl);
        return response.setComplete();
    }
}
